#include <windows.h>
#include <winhttp.h>
#include <string>
#include <vector>
#include <sstream>
#include <cstring>
#include <nlohmann.h>



// 调试输出函数(宽字符版)
void DebugOutput(const wchar_t* message) {
    OutputDebugStringW(message);
    OutputDebugStringW(L"\n");
}

// 将UTF-8字符串转换为宽字符串
static std::wstring Utf8ToWide(const std::string& utf8) {
    if (utf8.empty()) return L"";

    int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);
    if (wlen == 0) return L"";

    std::wstring wstr(wlen, 0);
    MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &wstr[0], wlen);

    // 移除末尾的null字符
    if (!wstr.empty() && wstr.back() == L'\0') {
        wstr.pop_back();
    }

    return wstr;
}

// 将宽字符串转换为UTF-8
static std::string WideToUtf8(const std::wstring& wstr) {
    if (wstr.empty()) return "";

    int ulen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
    if (ulen == 0) return "";

    std::string utf8(ulen, 0);
    WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &utf8[0], ulen, NULL, NULL);

    // 移除末尾的null字符
    if (!utf8.empty() && utf8.back() == '\0') {
        utf8.pop_back();
    }

    return utf8;
}

bool SendPdfPrintRequest(const std::vector<std::wstring>& pdfList,std::wstring serverIP,int port,std::wstring subpath,std::wstring printName) {
    HINTERNET hSession = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;
    BOOL bResults = FALSE;


    std::vector<std::string> pdfFiles;
    nlohmann::json jsonObject ;
    if (printName != L"")
        jsonObject["printName"] = WideToUtf8(printName);
    for(auto &it : pdfList){
    
        pdfFiles.push_back(WideToUtf8(it));
    
    }
    jsonObject["pdfList"] = pdfFiles;
    
    std::string jsonUtf8 = jsonObject.dump();
    
    if (jsonUtf8.empty()) {
        DebugOutput(L"Failed to convert JSON to UTF-8");
        return false;
    }

    


    // 初始化WinHTTP (W版本)
    hSession = WinHttpOpen(L"WinHTTP Example/1.0",
                         WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
                         WINHTTP_NO_PROXY_NAME,
                         WINHTTP_NO_PROXY_BYPASS, 0);
    if (!hSession) {
        DebugOutput(L"WinHttpOpen failed");
        return false;
    }

    // 创建连接 (W版本)
    hConnect = WinHttpConnect(hSession, serverIP.c_str(), port, 0);
    if (!hConnect) {
        DebugOutput(L"WinHttpConnect failed");
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 创建请求 (W版本)
    hRequest = WinHttpOpenRequest(hConnect, L"POST", subpath.c_str(),
                                NULL, WINHTTP_NO_REFERER,
                                WINHTTP_DEFAULT_ACCEPT_TYPES,
                                0);
    if (!hRequest) {
        DebugOutput(L"WinHttpOpenRequest failed");
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 添加请求头 (W版本)
    LPCWSTR headers = L"Content-Type: application/json; charset=utf-8\r\n";
    bResults = WinHttpAddRequestHeaders(hRequest, headers, -1,
                                      WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
    if (!bResults) {
        DebugOutput(L"WinHttpAddRequestHeaders failed");
    }

    // 发送请求 (使用UTF-8数据)
    bResults = WinHttpSendRequest(hRequest,
                                NULL, 0,
                                (LPVOID)jsonUtf8.data(),
                                (DWORD)jsonUtf8.size(),
                                (DWORD)jsonUtf8.size(), 0);
    if (!bResults) {
        DebugOutput(L"WinHttpSendRequest failed");
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 接收响应
    bResults = WinHttpReceiveResponse(hRequest, NULL);
    if (!bResults) {
        DebugOutput(L"WinHttpReceiveResponse failed");
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 读取响应数据
    DWORD dwSize = 0;
    DWORD dwDownloaded = 0;
    std::string response;
    
    do {
        if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) {
            DebugOutput(L"WinHttpQueryDataAvailable failed");
            break;
        }

        if (!dwSize) break;

        std::vector<char> buffer(dwSize + 1);
        if (!WinHttpReadData(hRequest, &buffer[0], dwSize, &dwDownloaded)) {
            DebugOutput(L"WinHttpReadData failed");
        } else {
            response.append(&buffer[0], dwDownloaded);
        }

    } while (dwSize > 0);

    if (!response.empty()) {
        DebugOutput((L"Server Response: " + Utf8ToWide(response)).c_str());
    }

    // 清理资源
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);

    return bResults;
}